<script setup lang="ts" name="inspection_list">
import {
  defineComponent,
  onMounted,
  onActivated,
  reactive,
  ref,
  toRaw,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, UploadUserFile } from 'element-plus'
import { deviceList, deviceSave, deviceLog } from "@/api/server_set_patrol";
import { getDeptTree } from "@/api/server_set_camera";

import { getInspectionTaskList } from "@/api/server_artificial";
import {
  downloadQRCode,
  addCruiserSave,
  deviceDelList,downloadInspectionPersonQRCode
} from "@/api/server_bill";
import { getUserList } from "@/api/server_set_account";
import { dataType } from "element-plus/lib/components/table-v2/src/common";

const router = useRouter();
const height = ref(0);
// const pageSize = ref(10);
const isEdit = ref(false);
const isBig = ref(false);
const tempIndex = ref();
const dialogVisible_add = ref(false);
const dialogVisible_map = ref(false);
const fileList = ref<any[]>([]);
const baseURL = import.meta.env.VITE_RES_URL + "/admin/config/uploadFile";
const formData = ref<any>({
  inspection_person_id: "",
  // name: "",
  // device_spec: "",
  // coordinate: "",
  // standard: "",
  // dept_id: "",
  // phone: "",
  // fileUrl: [],
  // user_id: "",
  // userInfo:{
  // },
  name: "",
  device_spec: "",
  coordinate: "",
  standard: "",
  dept_id: "",
  phone: "",
  files: "",
  user_id: "",
  fileUrl: [],
});
const fileUrl = ref("");
const deviceStatusOption = ref<any>({});
const deeptTypeOption = ref<any>({});
const deptOptions = ref([]);
const total = ref(0);
const totals = ref(0);
const List = ref([]);
const showDrawer = ref(false);
const showFileDrawer = ref(false);
const deviceLogList = ref<any[]>([]);
const deviceLogTotal = ref(0);
const device_id = ref();
const currentPage = ref(1);
const deviceLogForm = ref({
  page: 1,
  pageSize: 20,
});
const cascaderProps = reactive({
  label: "label",
  value: "id",
  children: "children",
  checkStrictly: true,
  emitPath: false,
});
const statusMap = ref<any>({
  normal: "正常",
  repairing: "维修中",
  broken: "报废",
});

const activeNames = ref(["collapse0"]);

// const addItem = () => {
//   isEdit.value = false;
//   formData.value = {
//     dept_type: "inner",
//   };
//   fileList.value = [];
//   dialogVisible_add.value = true;
// };

//列表数据
const getList = async (page: number) => {
  let res: any = await getInspectionTaskList({
    page: deviceLogForm.value.page,
    pageSize: deviceLogForm.value.pageSize,
  });

  if (res.result == "success") {
    List.value = res.list;
    deviceStatusOption.value = res.deviceStatusOption;
    deeptTypeOption.value = res.deptTypeOption;
    totals.value = res.total;
  }
  console.log("巡检点列表", res.list);
};
const getDeptInfo = async () => {
  let res: any = await getDeptTree({});
  if (res.result == "success") {
    deptOptions.value = res.deptTree;
  }
};
const formDatas = ref([]);

  const fileListlist = ref<UploadUserFile[]>([
  
])

const fileListitem = ref([]);
const edit = (data: any) => {
  isEdit.value = true;
  formData.value = {
    ...data,
  };

  formData.value.fileUrl = data.files;
  // fileListitem.value = data.files;
  // for (var i in fileListitem.value) {
  //   console.log("i", i);
  //   fileListitem.value.forEach((item: any) => {
  //     fileListlist.value = []
  //      fileListlist.value.push({
  //       name: item,
  //        url: item,
  //      });
  //   });
  // }


  // console.log("formData", formData.value.fileUrl);
  // let files = data.files ? JSON.parse(data.files) : [];
  // fileList.value = files.map((v: any) => {
  //   return {
  //     name: v.split("/").reverse()[0],
  //     url: v,
  //   };
  // });
  dialogVisible_add.value = true;
};

const download = async (data: any) => {
  let res = await downloadInspectionPersonQRCode({
    id: data.inspection_person_id,
  });
  if (res.result == "success") {
    
    console.log('res',res);
    
    const link = document.createElement("a");
    link.href = 'http://3ssaas.com' + res.pdfUrl;
    link.setAttribute("download", res.pdfUrl);
    document.body.appendChild(link);
    link.click();
  }
};
// 获取巡检人员
const userList = ref<any>([]);
const getListuser = async () => {
  let res: any = await getUserList({});
  if (res.result == "success") {
    userList.value = res.list;
    total.value = Number(res.total);
  }
};
// const record = (data: any) => {
//   showDrawer.value = true;
//   device_id.value = data.device_id;
//   getDeviceLog();
// };
const getDeviceLog = async () => {
  let res = await deviceLog({
    id: device_id.value,
    ...deviceLogForm.value,
  });
  if (res.result == "success") {
    deviceLogList.value = res.list;
    deviceLogTotal.value = Number(res.total);
  }
};
// const showFiles = (data: any) => {
//   formData.value = {
//     ...data,
//   };
//   isEdit.value = true;
//   showFileDrawer.value = true;
//   let files = data.files ? JSON.parse(data.files) : [];
//   fileList.value = files.map((v: any) => {
//     return {
//       name: v.split("/").reverse()[0],
//       url: v,
//     };
//   });
// };

// 删除
const remove = (data: any) => {
  ElMessageBox.confirm(`<span>确定要删除该巡检点吗？</span>`, "提 示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    dangerouslyUseHTMLString: true,
    type: "warning",
  }).then(async () => {
    let res = await deviceDelList({
      id: data.inspection_person_id,
    });
    if (res.result == "success") {
      getList(0);
      ElMessage({
        type: "success",
        message: "删除成功!",
      });
    }
  });
};
const handleSizeChange = (val: number) => {
  deviceLogForm.value.pageSize = val;
  getList(currentPage.value);
};

const handleCurrentChange = (val: number) => {
  deviceLogForm.value.page = val;
  getList(val);
};

const handlePreview = (file: any) => {
  // window.open(file.url);
};
const handleRemove = (file: any, fileList: any) => {
  // fileList.value = fileList;
};
const handleAvatarSuccess = (res: any, file: any, fileList: any) => {
  // file.url = res.fileUrl;
  // fileList.value = fileList;
};
const mapClick = (event: any) => {
  let offsetX = event.offsetX;
  let offsetY = event.offsetY;
  function setMapIndex(x: number, y: number) {
    let indexPoint: any = document.querySelector(".index-point");
    indexPoint.style.top = `${y}px`;
    indexPoint.style.left = `${x}px`;
    indexPoint.style.display = `block`;
    tempIndex.value = `${x},${y}`;
  }
  setMapIndex(offsetX, offsetY);
};
const openMap = () => {
  dialogVisible_map.value = true;
  setTimeout(() => {
    setMap();
  }, 100);
};
const doubleclick = (event: any) => {
  isBig.value = !isBig.value;
  if (!isBig.value) {
    setMap();
    return;
  }
  let offsetX = event.offsetX;
  let offsetY = event.offsetY;
  let mapBlock: any = document.querySelector(".setMapBlock-body");
  let mapId: any = document.querySelector(".setMapBlock");
  let mapBlockHeight = mapBlock.clientHeight;
  let mapBlockWidth = mapBlock.clientWidth;
  let mapIdHeight = mapId.clientHeight;
  let mapIdWidth = mapId.clientWidth;
  let left = -event.offsetX + mapBlockWidth / 2;
  let top = -event.offsetY + mapBlockHeight / 2;
  setTimeout(() => {
    if (left > 0) left = 0;
    if (left < mapBlockWidth - mapIdWidth) left = mapBlockWidth - mapIdWidth;
    if (top > 0) top = 0;
    if (top < mapBlockHeight - mapIdHeight) top = mapBlockHeight - mapIdHeight;
    mapId.style.transform = `scale(${1})`;
    mapId.style.left = `${left}px`;
    mapId.style.top = `${top}px`;
  }, 100);
  mapId.oncontextmenu = function () {
    return false;
  };

  mapId.addEventListener("mousedown", function (event: any) {
    event.stopPropagation();
    var code = event.which;
    if (code != 3 || !isBig.value) {
      return;
    }
    let left = parseInt(mapId.style.left);
    let top = parseInt(mapId.style.top);
    let ol = event.clientX;
    let ot = event.clientY;
    document.onmousemove = function (ev) {
      let l = left + ev.clientX - ol;
      let t = top + ev.clientY - ot;
      if (l > 0) l = 0;
      if (l < mapBlockWidth - mapIdWidth) l = mapBlockWidth - mapIdWidth;
      if (t > 0) t = 0;
      if (t < mapBlockHeight - mapIdHeight) t = mapBlockHeight - mapIdHeight;
      mapId.style.left = l + "px";
      mapId.style.top = t + "px";
    };
    document.onmouseup = function () {
      document.onmousemove = null;
    };
  });
};
const setMap = () => {
  let mapBlock: any = document.querySelector(".setMapBlock-body");
  let mapId: any = document.querySelector(".setMapBlock");
  let mapBlockHeight = mapBlock.clientHeight;
  let mapBlockWidth = mapBlock.clientWidth;
  let mapIdHeight = mapId.clientHeight;
  let mapIdWidth = mapId.clientWidth;
  let zoomVal = mapBlockHeight / mapIdHeight;
  let left = (mapBlockWidth - mapIdWidth) / 2;
  let top = (mapBlockHeight - mapIdHeight) / 2;
  mapId.style.transform = `scale(${zoomVal})`;
  mapId.style.left = `${left}px`;
  mapId.style.top = `${top}px`;
  mapId.oncontextmenu = function () {
    return false;
  };
};
const setIndex = () => {
  formData.value.coordinate = tempIndex.value;
  dialogVisible_map.value = false;
};

// 获取电话
const usephone = ref();
const change = (val: any) => {
  use(val);
};
const use = (val: any) => {
  usephone.value = userList.value.find((item: any) => item.user_id == val);
  formData.value.phone = usephone.value.phone;
};

const confirmAdd = async (val: number) => {
  //保存数据
  // let files = fileList.value.map((v) => {
  //   if (v.url) {
  //     return v.url;
  //   }
  // });

  let res: any = await addCruiserSave({
    // ...formData.value,
    id: isEdit.value ? formData.value.inspection_person_id : 0,
    name: formData.value.name,
    device_spec: formData.value.device_spec,
    coordinate: formData.value.coordinate,
    standard: formData.value.standard,
    dept_id: formData.value.dept_id,
    phone: formData.value.phone,
    files: formData.value.fileUrl,
    user_id: formData.value.user_id,
    // deptId: formData.value.dept_id,
    // deptType: formData.value.dept_type,
    // deptMark: formData.value.dept_mark,
    // factoryPhone: formData.value.factory_phone,
    // files: files.join(","),
  });
  if (res.result === "success") {
    ElMessage({
      type: "success",
      message: "保存成功!",
    });
    dialogVisible_add.value = false;
    //添加完成后重新获取数据
    getList(0);
  }
};

onMounted(() => {
  let pageTable: any = document.querySelector(".page-table");
  height.value = pageTable.clientHeight;

  getList(0);
  getDeptInfo();
  getListuser();
});
// 上传图片
// token
const headersObj = ref({
  TOKEN: window.localStorage.getItem("token"),
});
const success = (response: any) => {
  if (response.result === "success") {
    formData.value.fileUrl.push(response.fileUrl);
    ElMessage({
      type: "success",
      message: "已选择图片",
    });
  }
  console.log("formData.value.fileUrl", formData.value.fileUrl);
};
const dialogVisibleab = ref(false);
const dialogImageUrlab = ref("");
</script>

<template>
  <div class="patrol-page">
    <div class="page-top">
      <h4>巡检点位列表</h4>
      <!-- <el-button type="primary" size="small" @click="addItem"
          >新增设备</el-button
        > -->
    </div>
    <div class="page-table">
      <el-table ref="table" v-if="height" :data="List" :height="height">
        <el-table-column
          label="编号"
          prop="inspection_person_id"
        ></el-table-column>
        <el-table-column label="巡检点名称" prop="name"></el-table-column>
        <el-table-column
          label="巡检设备型号"
          prop="device_spec"
        ></el-table-column>
        <el-table-column
          label="巡检点负责人"
          prop="userInfo.name"
        ></el-table-column>
        <el-table-column
          label="部门"
          prop="userInfo.deptName"
        ></el-table-column>
        <el-table-column label="地图坐标" prop="coordinate"></el-table-column>
        <!-- <el-table-column label="售后" prop="dept_type">
            <template #default="{ row }">
              <span>{{ deeptTypeOption[row.dept_type] }}</span>
            </template>
          </el-table-column> -->
        <el-table-column label="联系电话" prop="phone"></el-table-column>
        <el-table-column label="巡检标准" prop="standard"></el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <el-button link size="small" @click="edit(row)">编辑</el-button>
            <el-button link size="small" @click="remove(row)">删除</el-button>
            <!-- <el-button link size="small" @click="showFiles(row)"
                >查看资料</el-button
              >
              <el-button link size="small" @click="record(row)"
                >报修记录</el-button
              > -->
            <el-button link size="small" @click="download(row)"
              >下载二维码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:currentPage="currentPage"
        :page-sizes="[20, 30, 40, 50]"
        :page-size="deviceLogForm.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="totals"
      >
      </el-pagination>
    </div>

    <el-dialog
      :close-on-click-modal="true"
      :title="isEdit ? '编辑巡检点' : '新增巡检点'"
      v-model="dialogVisible_add"
      width="650px"
    >
      <el-form ref="form" :model="formData" label-width="130px">
        <el-form-item label="巡检点编号" v-if="isEdit">
          <el-input
            type="number"
            disabled
            placeholder="请输入"
            v-model="formData.inspection_person_id"
          ></el-input>
        </el-form-item>
        <el-form-item label="巡检点名称">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="formData.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="巡检设备型号">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="formData.device_spec"
          ></el-input>
        </el-form-item>
        <el-form-item label="巡检点负责人">
          <el-select
            @change="change"
            filterable
            clearable
            style="width: 80%"
            v-model="formData.user_id"
            placeholder="请选择"
          >
            <el-option
              :value="c.user_id"
              :label="c.name"
              :key="index"
              v-for="(c, index) in userList"
            >
              <span style="float: left">{{ c.name }}</span>
              <span style="float: right; font-size: 13px">{{ c.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检点负责人电话">
          <el-input
            v-model="formData.phone"
            disabled
            placeholder="巡检点负责人电话"
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader
            style="width: 100%"
            placeholder="请选择部门"
            :props="cascaderProps"
            v-model="formData.dept_id"
            :options="deptOptions"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="地图坐标">
          <div class="btn-act">
            <el-input
              class="btn-input"
              type="text"
              placeholder="坐标"
              disabled
              v-model="formData.coordinate"
            ></el-input>
            <el-button class="btn" @click="openMap()" type="primary" plain
              >设置位置</el-button
            >
          </div>
        </el-form-item>

        <!-- <el-form-item label="上传图片">
          <el-upload
            name="uploadFile"
            v-model:file-list="fileListlist"
            action="http://.world/common/overall/uploadFile"
            list-type="picture-card"
            :headers="headersObj"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="success"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisibleab" width="600px">
            <img
              style="width: 550px"
              w-full
              :src="dialogImageUrlab"
              alt="Preview Image"
            />
          </el-dialog>
        </el-form-item> -->

        <el-form-item label="巡检标准">
          <el-input
            v-model="formData.standard"
            maxlength="30"
            placeholder="此处有高压电！注意安全！"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <el-dialog
        :close-on-click-modal="false"
        title="提示"
        :destroy-on-close="true"
        v-model="dialogVisible_map"
        width="800"
      >
        <div class="setMapBlock-body">
          <div id="rightClickDiv">
            <div class="addProductSpan liHover">选择位置</div>
          </div>
          <div class="setMapBlock" @dblclick="doubleclick" @click="mapClick">
            <img src="@/assets/image/home/map.png" />
            <div class="index-point" style="top: 1px; left: 1px">
              <img src="@/assets/image/home/lan1.png" />
            </div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible_map = false">取 消</el-button>
            <el-button type="primary" @click="setIndex()">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <template #footer>
        <el-button @click="dialogVisible_add = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.patrol-page {
  width: 100%;
  height: 100%;
  .page-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .page-table {
    margin: 16px 0;
    height: calc(100% - 100px);
  }
  .status_icon {
    width: 10px;
    height: 10px;
    border-radius: 10px;
    display: inline-block;
    vertical-align: middle;
    position: relative;
    bottom: 2px;
  }
  .normal {
    background: #2fcc95;
  }
  .broken {
    background: red;
  }
  .repairing {
    background: #ff7300;
  }
  .bx-status {
    padding: 5px;
    border-radius: 5px;
    display: inline-block;
    vertical-align: middle;
    line-height: 16px;
    color: #fff;
    font-size: 12px;
    margin-right: 10px;
  }

  .el-drawer__header {
    margin-bottom: 10px;
  }
  .drawer-block {
    padding: 0 20px;
    height: calc(100% - 40px);
    overflow: auto;
  }

  .image_list {
    display: flex;
    flex-wrap: wrap;
  }
  .image_list .image-item {
    width: 80px;
    height: 80px;
    border: 1px dashed #ccc;
    margin: 9px;
  }

  .el-collapse {
    border: none !important;
  }
  .el-collapse-item {
    margin-bottom: 10px;
    text-align: left;
  }
  .el-collapse-item__content {
    background: rgba(255, 255, 255, 0.03);
    border-radius: 4px;
    border: 1px solid #f0f0f0;
    padding: 0 10px;
  }
  .el-collapse-item__wrap {
    border: none !important;
  }
  .el-collapse-item__header {
    background: #222121;
    border-radius: 5px;
    border-bottom: unset;
    padding-left: 10px;
  }
}
.setMapBlock-body {
  width: 100%;
  height: 500px;
  overflow: hidden !important;
  position: relative;
  border: 1px solid #000;
}
.setMapBlock {
  display: inline-block;
  position: absolute;
  cursor: pointer;
}
.setMapBlock .index-point {
  width: 0;
  height: 0;
  position: absolute;
  display: none;
}
.setMapBlock .index-point img {
  position: absolute;
  width: 144px;
  left: -144px;
  bottom: 0;
}
.btn-act {
  display: flex;
  .btn-input {
    width: 100px;
  }
}
.btn {
  margin-left: 15px;
}
</style>
